<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 用户类  
 */
class AdminTask extends CI_Controller{
    public function __construct(){
        parent::__construct();
        $this->load->library('request');  //自定义
        $this->load->library('response'); //自定义
        $this->load->library('session'); //公共
        $reqOrigin = isset($_SERVER['HTTP_ORIGIN'])?$_SERVER['HTTP_ORIGIN']:'';
        $configOrigin = $this->config->item("allowOrigin");
        if(in_array($reqOrigin,$configOrigin)){
            header("Access-Control-Allow-Credentials:true");
            header("Access-Control-Allow-Headers:Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild");
            header("Access-Control-Allow-Methods:PUT, POST, GET, DELETE, OPTIONS");
            header("Access-Control-Allow-Origin:$reqOrigin"); 
        }
    }

    /**
     * [loginStatus description]
     * @return [type] [description]
     */
    private function loginStatus(){
        if(isset($this->session->admin_user_id) && $this->session->admin_user_id){
            return array("admin_user_id"=>$this->session->admin_user_id,"status"=>0);
        }
        else{
            return array("status"=>2006);
        }
    } 

    /**
     * [createTask description]
     * @return [type] [description]
     */
    public function createTask(){
        if($this->input->method()=="post"){       
            //1登陆状态
            $login = $this->loginStatus();
            if($login['status']){
                $this->response->sendData($login['status']);return;
            }

            $admin_user_id = $login['admin_user_id'];
            // echo $admin_user_id;exit;
            //2获取数据
            $data = $this->request->getPostRawData();
            log_message('info', 'createTask/createTask,data:'.json_encode($data));     
            if(!$data['name'] || !$data['type'] || !$data['reward'] || !$data['closeDate'] || !$data['instruction']|| !$data['cover']|| !$data['notes'] || !$data['taskCount'] ){
                $this->response->sendData(1000);return;
            }
            if($data['closeTime']){
                $markPos = strpos( $data['closeTime'],":");
                if($markPos>=2){
                    $data['closeTime'] = substr($data['closeTime'], $markPos-2,8);
                }
                $pattern = '/^[\d]{1,2}:[\d]{1,2}:[\d]{1,2}$/';
                if(!preg_match($pattern, $data['closeTime'])){
                    $this->response->sendData(1000);return;
                }
            }
            //登陆操作
            $this->load->model("userModel");
            $data['platform'] = '后台';
            $ret = $this->userModel->createTask($admin_user_id,$data);
            $out_data['success'] = $ret['success'];
            $out_data['fail'] = $ret['fail'];
            $this->response->sendData($ret['status'],'',$out_data);return;
        }
        else{
            $status = 1001;
        }
        $this->response->sendData($status);

    }

    /**
     * [taskObtainList description]
     * @return [type] [description]
     */
    public function taskObtainList(){
        if($this->input->method()=="get"){       
            //1登陆状态
            $login = $this->loginStatus();
            if($login['status']){
                $this->response->sendData($login['status']);return;
            }
            $admin_user_id = $login['admin_user_id'];
            // echo $admin_user_id;exit;
            //2获取数据
            $data = $this->request->getGetData(["page","size",'keyword','obtainStatus','status']);
            log_message('info', 'adminuser/taskObtainList,data:'.json_encode($data));     
            if(!$data['page'] || !$data['size'] ){
                $this->response->sendData(1000);return;
            }
            //3查询
            $this->load->model("taskModel");
            $ret = $this->taskModel->adminTaskObtainList($data);          
            //4查询基础的统计
            $ret['out_data']['typeOne'] = $this->taskModel->adminTaskObtainStatistic(0);   
            $ret['out_data']['typeTwo'] = $this->taskModel->adminTaskObtainStatistic(1);   
            $ret['out_data']['typeThree'] = $this->taskModel->adminTaskObtainStatistic(6);   
            $ret['out_data']['typeFour'] = $this->taskModel->adminTaskObtainStatistic(3);   
            $ret['out_data']['typeFive'] = 0;//$this->taskModel->adminTaskObtainStatistic(5);   
            
            $this->response->sendData($ret['status'],$ret['data'],$ret['out_data']);return;
        }
        else{
            $status = 1001;
        }
        $this->response->sendData($status);
    }

    /**
     * [taskObtainDetail description]
     * @return [type] [description]
     */
    public function taskObtainDetail(){
        if($this->input->method()=="get"){       
            //1登陆状态
            $login = $this->loginStatus();
            if($login['status']){
                $this->response->sendData($login['status']);return;
            }
            $admin_user_id = $login['admin_user_id'];
            // echo $admin_user_id;exit;
            //2获取数据
            $data = $this->request->getGetData(["obtainId"]);
            log_message('info', 'adminuser/taskObtainDetail,data:'.json_encode($data));     
            if(!$data['obtainId'] ){
                $this->response->sendData(1000);return;
            }
            //3查询
            $this->load->model("taskModel");
            $ret = $this->taskModel->adminTaskObtainDetail($data['obtainId']);          
            $this->response->sendData($ret['status'],'',$ret['out_data']);return;
        }
        else{
            $status = 1001;
        }
        $this->response->sendData($status);
    }

    /**
     * [confirmTask 后台把任务提交给委托方]
     * @return [type] [description]
     */
    public function confirmTask(){
        if($this->input->method()=="post"){       
            //1登陆状态
            $login = $this->loginStatus();
            if($login['status']){
                $this->response->sendData($login['status']);return;
            }
            $admin_user_id = $login['admin_user_id'];
            // echo $admin_user_id;exit;
            //2获取数据
            $data = $this->request->getPostRawData();
            log_message('info', 'adminTask/confirmTask,data:'.json_encode($data));     
            if(!$data['obtainId'] ){
                $this->response->sendData(1000);return;
            }            
            $this->load->model("userModel");
            $data['platform'] = '后台';
            $ret = $this->userModel->adminConfirmTask($admin_user_id,$data);
            $this->response->sendData($ret['status']);return;
        }
        else{
            $status = 1001;
        }
        $this->response->sendData($status);
    }

     /**
     * [taskApplyDetail 某个任务的申请（申请延期、申请取消）]
     * @return [type] [description]
     */
    public function taskApplyDetail(){
        if($this->input->method()=="get"){       
            //1登陆状态
            $login = $this->loginStatus();
            if($login['status']){
                $this->response->sendData($login['status']);return;
            }
            $admin_user_id = $login['admin_user_id'];
            // echo $admin_user_id;exit;
            //2获取数据
            $data = $this->request->getGetData(["obtainId","obtainStatus"]);
            log_message('info', 'adminuser/taskApplyDetail,data:'.json_encode($data));     
            if(!$data['obtainId'] ){
                $this->response->sendData(1000);return;
            }
            //3查询基础数据
            $this->load->model("taskModel");
            $detailRet = $this->taskModel->adminTaskObtainDetail($data['obtainId']);  
            if($detailRet['status'])        {
                $this->response->sendData($detailRet['status']);return;
            }
            // var_dump($detailRet['out_data']);exit;
            $ret['out_data'] = $detailRet['out_data'];
            //4延期的数据
            $applyRet = $this->taskModel->admintaskApplyDetail($data);          
            if($applyRet['status']){
                $this->response->sendData($applyRet['status']);return;                
            }
            // var_dump($applyRet);exit;
            $ret['out_data']->applyInstruct = isset($applyRet['out_data']->instruction)?$applyRet['out_data']->instruction:"";
            $ret['out_data']->applyCloseDate = isset($applyRet['out_data']->close_date)?$applyRet['out_data']->close_date:"";
            $ret['out_data']->applyCloseTime = isset($applyRet['out_data']->close_time)?$applyRet['out_data']->close_time:"";
            $this->response->sendData(0,'',$ret['out_data']);return;
        }
        else{
            $status = 1001;
        }
        $this->response->sendData($status);
    }
 
    /**
     * [delayTask 后台同意延期任务]
     * @return [type] [description]
     */
    public function delayTask(){
        if($this->input->method()=="post"){       
            //1登陆状态
            $login = $this->loginStatus();
            if($login['status']){
                $this->response->sendData($login['status']);return;
            }
            $admin_user_id = $login['admin_user_id'];
            // echo $admin_user_id;exit;
            //2获取数据
            $data = $this->request->getPostRawData();
            log_message('info', 'adminTask/delayTask,data:'.json_encode($data));     
            if(!$data['obtainId'] ){
                $this->response->sendData(1000);return;
            }            
            $this->load->model("userModel");
            $ret = $this->userModel->adminDelayTask($admin_user_id,$data);
            $this->response->sendData($ret['status']);return;
        }
        else{
            $status = 1001;
        }
        $this->response->sendData($status);
    } 

    /**
     * [cancelTask 后台同意取消任务，同时确定是否要重新发布]
     * @return [type] [description]
     */
    public function cancelTask(){
        if($this->input->method()=="post"){       
            //1登陆状态
            $login = $this->loginStatus();
            if($login['status']){
                $this->response->sendData($login['status']);return;
            }
            $admin_user_id = $login['admin_user_id'];
            // echo $admin_user_id;exit;
            //2获取数据
            $data = $this->request->getPostRawData();
            log_message('info', 'adminTask/cancelTask,data:'.json_encode($data));     
            if(!$data['obtainId']){
                $this->response->sendData(1000);return;
            }            
            $this->load->model("userModel");
            $ret = $this->userModel->adminCancelTask($admin_user_id,$data);
            $this->response->sendData($ret['status']);return;
        }
        else{
            $status = 1001;
        }
        $this->response->sendData($status);
    }

    /**
     * [updateTask 委托方同意/不同意方案，需要修改]
     * @return [type] [description]
     */
    public function updateTask(){
        if($this->input->method()=="post"){       
            //1登陆状态
            $login = $this->loginStatus();
            if($login['status']){
                $this->response->sendData($login['status']);return;
            }
            $admin_user_id = $login['admin_user_id'];
            // echo $admin_user_id;exit;
            //2获取数据
            $data = $this->request->getPostRawData();
            log_message('info', 'adminTask/updateTask,data:'.json_encode($data));     
            if(!$data['obtainId'] || $data['status']==''){
                $this->response->sendData(1000);return;
            }            

            //3操作数据
            $this->load->model("userModel");
            $ret = $this->userModel->adminUpdateTask($admin_user_id,$data);
            $this->response->sendData($ret['status']);return;
        }
        else{
            $status = 1001;
        }
        $this->response->sendData($status);

    }

    /**
     * [do_upload description]
     * @return [type] [description]
     */
    public function do_upload()
    {

        $reqData = $this->request->getPostData();
        log_message('info', 'adminTask/do_upload,data:'.json_encode($reqData)); 
        //1验证登录状态 
        $login = $this->loginStatus();
        if($login['status']){
            $this->response->sendData($login['status']);return;
        }
        
        $userId = $login['admin_user_id'];
        $realPath = dirname(dirname(dirname(__FILE__))).'/uploads/'.date("Y-m-d");
        $pathstatus = $this->checkPath($realPath);
        $path = "uploads/".date("Y-m-d");
        $config['upload_path']      = "./$path/";
        $config['allowed_types']    = 'gif|jpg|png';
        $config['max_size']     = 10000;
        // $config['max_width']        = 1024;
        // $config['max_height']       = 768;
        $config['file_name']       = $userId.time().rand(1000,9999);

        $this->load->library('upload', $config);

        if ( ! $this->upload->do_upload('file')){
            $error = array('error' => $this->upload->display_errors());
            log_message('info', 'adminTask/do_upload,error:'.json_encode($error)); 
            $this->response->sendData(2023);return;
        }
        else
        {
            $data = array('upload_data' => $this->upload->data());
            // var_dump($data);exit;
            //转相对路径
            $full_path = $data['upload_data']['full_path'];
            $position = strpos($full_path,$path);
            // echo $position;exit;
            $ret['fileUrl'] = $this->config->item('base_url') . substr($full_path, $position-1);
            $this->response->sendData(0,'',$ret);return;
        }
    }

     /**
     * 检查目录是否可写
     * @param  string   $path    目录
     * @return boolean
     */
    protected function checkPath($path)
    {
        if (is_dir($path)) {
            return true;
        }

        if (mkdir($path, 0755, true)) {
            return true;
        } else {
            $this->error = "目录 {$path} 创建失败！";
            return false;
        }
    }


     /**
     * [taskObtainAwardDetail description]
     * @return [type] [description]
     */
    public function taskObtainAwardDetail(){
        if($this->input->method()=="get"){       
            //1登陆状态
            $login = $this->loginStatus();
            if($login['status']){
                $this->response->sendData($login['status']);return;
            }
            $admin_user_id = $login['admin_user_id'];
            // echo $admin_user_id;exit;
            //2获取数据
            $data = $this->request->getGetData(["obtainId"]);
            log_message('info', 'adminuser/taskObtainAwardDetail,data:'.json_encode($data));     
            if(!$data['obtainId'] ){
                $this->response->sendData(1000);return;
            }
            //3查询
            $this->load->model("taskModel");
            $ret = $this->taskModel->taskObtainAwardDetail($data['obtainId']);          
            $this->response->sendData($ret['status'],'',$ret['out_data']);return;
        }
        else{
            $status = 1001;
        }
        $this->response->sendData($status);
    }


}
